package com.ztgf.shopping.service.shop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.commodity.models.dto.BrandInfoAuditDTO;
import com.ztgf.commodity.models.dto.BrandInfoDTO;
import com.ztgf.commodity.models.service.IBrandInfoAuditService;
import com.ztgf.commodity.models.service.IBrandInfoService;
import com.ztgf.commodity.models.service.ICommodityEvaluationService;
import com.ztgf.commodity.models.service.ICommodityInfoService;
import com.ztgf.commodity.models.vo.CommodityEvaluationScoreVO;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.CustomizeUtil;
import com.ztgf.common.utils.DateUtils;
import com.ztgf.common.utils.SignUtils;
import com.ztgf.common.utils.StrUtils;
import com.ztgf.file.models.vo.FileInfoVO;
import com.ztgf.message.model.bo.MessageAnnouncementSaveBO;
import com.ztgf.message.model.constant.MessageTopicType;
import com.ztgf.message.model.dto.ResponseDTO;
import com.ztgf.message.model.enums.MessageEnum;
import com.ztgf.message.model.service.IKafkaProducerService;
import com.ztgf.order.models.dto.OrderInfoDTO;
import com.ztgf.order.models.dto.OrderPaymentScaleDTO;
import com.ztgf.order.models.dto.OrderPaymentTypeDTO;
import com.ztgf.order.models.dto.OrderReturnCommodityDTO;
import com.ztgf.order.models.service.IOrderInfoService;
import com.ztgf.order.models.service.IOrderPaymentScaleService;
import com.ztgf.order.models.service.IOrderPaymentTypeService;
import com.ztgf.order.models.service.IOrderReturnCommodityService;
import com.ztgf.search.models.dto.EsShopDTO;
import com.ztgf.search.models.service.IShopSearchService;
import com.ztgf.shopping.common.config.YmlConfig;
import com.ztgf.shopping.mapper.shop.ShopInfoMapper;
import com.ztgf.shopping.mapper.shop.ShopQualificationMapper;
import com.ztgf.shopping.models.bo.shop.*;
import com.ztgf.shopping.models.constant.ShoppingConstant;
import com.ztgf.shopping.models.dto.audit.AuditDTO;
import com.ztgf.shopping.models.dto.audit.ProcessVO;
import com.ztgf.shopping.models.dto.shop.*;
import com.ztgf.shopping.models.enums.ShoppingCodeEnum;
import com.ztgf.shopping.models.service.audit.IAuditService;
import com.ztgf.shopping.models.service.shop.*;
import com.ztgf.shopping.models.vo.audit.RegisterShopVO;
import com.ztgf.shopping.models.vo.shop.*;
import com.ztgf.sms.models.bo.SmsInfoSaveBO;
import com.ztgf.sms.models.dto.email.EmailInfoDTO;
import com.ztgf.sms.models.service.ISmsInfoService;
import com.ztgf.sys.models.service.ISysAreaService;
import com.ztgf.user.models.dto.UserImDTO;
import com.ztgf.user.models.dto.UserInfoDTO;
import com.ztgf.user.models.dto.UserLoginDTO;
import com.ztgf.user.models.service.IUserImService;
import com.ztgf.user.models.service.IUserInfoService;
import com.ztgf.user.models.service.IUserLoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

import static com.ztgf.common.utils.UtilConstants.isNull;


/**
 * 店铺表控制器
 *
 * @author zhanghualang
 * @Date 2020-05-28 14:35:39
 */
@Slf4j
@DubboService
@Lazy
public class ShopInfoServiceImpl extends ServiceImpl<ShopInfoMapper, ShopInfoDTO> implements IShopInfoService {

    @Resource
    private YmlConfig ymlConfig;
    @Autowired
    private ShopQualificationMapper shopQualificationMapper;
    @Autowired
    private IShopReceiveCardService iShopReceiveCardService;
    @Autowired
    private IShopSalesAreaService iShopSalesAreaService;
    @Autowired
    private IShopCategoryRelationService iShopCategoryRelationService;
    @Autowired
    private IShopSpecificationCategoryRelationService iShopSpecificationCategoryRelationService;
    @DubboReference
    private ICommodityInfoService iCommodityInfoService;
    @Autowired
    private IShopEarnestMoneyLogService iShopEarnestMoneyLogService;
    @DubboReference
    private IUserLoginService iUserLoginService;
    @DubboReference
    private ICommodityEvaluationService iCommodityEvaluationService;
    @DubboReference
    private IOrderInfoService iOrderInfoService;
    @Autowired
    private IShopBrandRelationService iShopBrandRelationService;
    @Autowired
    private IShopEarnestMoneyService iShopEarnestMoneyService;
    @Autowired
    private IShopAnnualFeeService iShopAnnualFeeService;
    @DubboReference
    private IUserInfoService iUserInfoService;
    @DubboReference
    private IBrandInfoService iBrandInfoService;
    @Autowired
    private IShopUserRelationService iShopUserRelationService;
    @Autowired
    private IShopInfoAuditService iShopInfoAuditService;
    @Autowired
    private IShopInfoAuditLogService iShopInfoAuditLogService;
    @Autowired
    private IShopQualificationAuditService iShopQualificationAuditService;
    @Autowired
    private IShopCategoryRelationAuditService iShopCategoryRelationAuditService;
    @DubboReference
    private IBrandInfoAuditService iBrandInfoAuditService;
    @Autowired
    private IShopBrandRelationAuditService iShopBrandRelationAuditService;
    @DubboReference
    private IUserImService iUserImService;
    @DubboReference
    private ISysAreaService iSysAreaService;
    @DubboReference
    private ISmsInfoService iSmsInfoService;
    @DubboReference
    private IKafkaProducerService kafkaProducerService;
    @Autowired
    private IShopBlacklistService shopBlacklistService;
    @DubboReference
    private IAuditService auditService;
    @Autowired
    private IShopCollectService iShopCollectService;
    @DubboReference
    private IShopSearchService shopSearchService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private IShopReceiveCardService shopReceiveCardService;
    @DubboReference
    private IOrderPaymentScaleService orderPaymentScaleService;
    @DubboReference
    private IOrderReturnCommodityService orderReturnCommodityService;
    @DubboReference
    private IOrderPaymentTypeService orderPaymentTypeService;

    @Value("${file.url}")
    private String fileUrl;
    @Value("${im.riclurl}")
    private String imUrl;

    @Override
    public List<ShopInfoVO> getByShopIds(List<Long> shopIds) {
        return baseMapper.getByShopIds(shopIds);
    }

    @Override
    public boolean updateAdminFreeze(Long id, Long userId) {
        ShopInfoDTO dto = new ShopInfoDTO();
        dto.setId(id);
        //冻结状态 0未冻结，1冻结 2关店 defaultValue
        dto.setAdminFrozenStatus(1);
        dto.setUpdateUserId(userId);
        boolean flag = this.updateById(dto);
        if (flag) {
            //发送短信，发送站内信
            addSms(id);
            urgeSignContact("您的店铺状态发生变更", id, 1, 1);//发送消息
            //所有产品下架
            iCommodityInfoService.updateNotPublishByShopId(id, "店铺冻结");
            // TODO admin冻结店铺移除ES
            shopSearchService.deleteData("index_shop_2020", "shop", id.toString());
        }
        return flag;
    }

    /*
     * @description:判断店铺是否关店（冻结）
     * @author: chenyu.wang
     * @date: 2020-09-17
     * @return: true:正常，false:此店铺已冻结
     */
    @Override
    public boolean checkShopIsClose(Long shopId) {
        ShopInfoDTO shopInfoDTO = this.selectById(shopId);
        if (shopInfoDTO == null) {
            return false;
        }
        if (shopInfoDTO.getMerchantType().equals(1) && shopInfoDTO.getFrozenStatus().equals(0) && shopInfoDTO.getAdminFrozenStatus().equals(0)) {
            return true;
        }
        return false;
    }

    @Override
    public List<ShopInfoDTO> queryCloseStatus(Long minNo, Integer pageNo) {
        Wrapper<ShopInfoDTO> wrapper = new EntityWrapper<>();
        //关店流程状态 0未开启，1检测中（检测订单）.2关店中（关店倒计时中）
        wrapper.eq("close_status", 1);
        wrapper.ge("id", minNo);
        wrapper.orderBy("id", true);
        return baseMapper.selectPage(new Page(0, pageNo), wrapper);
    }

    @Override
    public List<ShopInfoDTO> queryCloseShop(Long minNo, Integer pageNo) {
        Wrapper<ShopInfoDTO> wrapper = new EntityWrapper<>();
        //关店流程状态 0未开启，1检测中（检测订单）.2关店中（关店倒计时中）
        wrapper.eq("close_status", 2);
        wrapper.ge("id", minNo);
        wrapper.orderBy("id", true);
        return baseMapper.selectPage(new Page(0, pageNo), wrapper);
    }

    @Override
    public boolean updatePayTypeByShopId(Long shopId, Integer payType) {
        ShopInfoDTO shopInfoDTO = selectById(shopId);
        if (null == shopInfoDTO) {
            return false;
        }
        shopInfoDTO.setShopPayType(payType);
        //发送站内信
        sendMessagePayTypeChange(shopId);
        return updateById(shopInfoDTO);
    }

    /**
     * 发送站内消息 当店铺支付类型发生改变
     */
    private void sendMessagePayTypeChange(Long shopId) {
        ResponseDTO responseDTO = new ResponseDTO();
        responseDTO.setMessageId(shopId + "");
        MessageAnnouncementSaveBO messageAnnouncementSaveBO = new MessageAnnouncementSaveBO();
        messageAnnouncementSaveBO.setType(MessageEnum.SYS_MESSAGE.getCode());
        messageAnnouncementSaveBO.setShopId(shopId);
        messageAnnouncementSaveBO.setTitle("支付类型发生改变，请查看。");
        messageAnnouncementSaveBO.setContent("支付类型发生改变，请查看。");
        messageAnnouncementSaveBO.setTextType(1);
        messageAnnouncementSaveBO.setJumpType(MessageEnum.MESSAGE_SHOW.getCode() + "");
        messageAnnouncementSaveBO.setShopType(MessageEnum.SHOP_TYPE_2.getCode());
        messageAnnouncementSaveBO.setKey(shopId + "");
        responseDTO.setData(messageAnnouncementSaveBO);
        kafkaProducerService.senMessage(JSON.toJSONString(responseDTO), MessageTopicType.COMMENT_MESSAGE_TOPIC);
    }

    @Override
    public boolean add(ShopInfoSaveBO saveBO) {
        Long id = ymlConfig.getPkId();
        ShopInfoDTO dto = new ShopInfoDTO();
        BeanUtils.copyProperties(saveBO, dto);
        //更新成为卖家
        dto.setMerchantType(1);
        dto.setId(id);
        return this.insert(dto);
    }

    @Override
    public ShopInfoVO selectVoById(Long id) {
        ShopInfoVO shopInfoVO = new ShopInfoVO();
        ShopInfoDTO shopInfoDTO = this.selectById(id);
        if (shopInfoDTO == null) {
            return shopInfoVO;
        }

        //根据user_id获取userLogin 信息
        Wrapper<UserLoginDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", shopInfoDTO.getUserId());
        UserLoginDTO userLoginDTO = iUserLoginService.selectOne(wrapper);
        if (userLoginDTO == null) {
            return shopInfoVO;
        }

        //根据user_id获取userinfo 信息
        UserInfoDTO userInfoDTO = iUserInfoService.selectById(shopInfoDTO.getUserId());
        if (userInfoDTO == null) {
            return shopInfoVO;
        }

        //将手机号和邮箱加入vo
        BeanUtils.copyProperties(shopInfoDTO, shopInfoVO);
        shopInfoVO.setMobile(userLoginDTO.getMobile());
        shopInfoVO.setEmail(userLoginDTO.getEmail());
        shopInfoVO.setContactName(userInfoDTO.getContactName());

        return shopInfoVO;
    }

    @Override
    public ShopInfoVO selectVoByDomain(String domain) {
        ShopInfoVO shopInfoVO = new ShopInfoVO();
        Wrapper<ShopInfoDTO> shopInfoWrapper = new EntityWrapper<>();
        shopInfoWrapper.eq("domain", domain);
        ShopInfoDTO shopInfoDTO = this.selectOne(shopInfoWrapper);
        if (shopInfoDTO == null) {
            return shopInfoVO;
        }

        //根据user_id获取userLogin 信息
        Wrapper<UserLoginDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", shopInfoDTO.getUserId());
        UserLoginDTO userLoginDTO = iUserLoginService.selectOne(wrapper);
        if (userLoginDTO == null) {
            return shopInfoVO;
        }

        //根据user_id获取userinfo 信息
        UserInfoDTO userInfoDTO = iUserInfoService.selectById(shopInfoDTO.getUserId());
        if (userInfoDTO == null) {
            return shopInfoVO;
        }

        //将手机号和邮箱加入vo
        BeanUtils.copyProperties(shopInfoDTO, shopInfoVO);
        shopInfoVO.setMobile(userLoginDTO.getMobile());
        shopInfoVO.setEmail(userLoginDTO.getEmail());
        shopInfoVO.setContactName(userInfoDTO.getContactName());

        return shopInfoVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(ShopInfoUpdateBO updateBO) {
        /**
         * 1保存审核表
         * 2保存审核日志
         * 3保存店铺品牌关系审核表
         * 4保存资质审核表
         * 5保存品牌类目审核表
         * 5.新增品牌
         */

        Long shopId = updateBO.getId();
        ShopInfoDTO shopInfoDTO = this.selectById(shopId);
        Long userId = shopInfoDTO.getUserId();

        ShopReceiveCardSaveBO shopReceiveCardSaveBO = JSON.parseObject(updateBO.getShopReceiveCardSaveBO(), ShopReceiveCardSaveBO.class);
        /**
         * 保存审核表
         */
        ShopInfoAuditDTO shopInfoAuditDTO = new ShopInfoAuditDTO();
        Long shopInfoAuditId = ymlConfig.getPkId();
        shopInfoAuditDTO.setId(shopInfoAuditId);
        shopInfoAuditDTO.setUserId(userId);
        shopInfoAuditDTO.setCreateUserId(userId);
        shopInfoAuditDTO.setShopId(shopId);
        shopInfoAuditDTO.setName(shopInfoDTO.getName());//公司名称
        shopInfoAuditDTO.setAddress(shopInfoDTO.getAddress());//公司地址
        shopInfoAuditDTO.setDomain(updateBO.getDomain());//二级域名
        shopInfoAuditDTO.setShopName(updateBO.getShopName());//店铺名称
        shopInfoAuditDTO.setShopRealName(updateBO.getShopRealName());//店铺名称
        shopInfoAuditDTO.setShopAbbreviation(updateBO.getShopAbbreviation());//店铺简称
        shopInfoAuditDTO.setBankName(shopReceiveCardSaveBO.getBankName());//开户银行名称
        shopInfoAuditDTO.setBankCardNo(shopReceiveCardSaveBO.getBankCardNo());//开户卡号
        shopInfoAuditDTO.setBankAddress(shopReceiveCardSaveBO.getBankAddress());//开户行地址
        shopInfoAuditDTO.setShopType(updateBO.getType());//店铺类型 0专营店、1专卖店、2旗舰店、3自营店
        shopInfoAuditDTO.setType(1);//审核类型 0注册，1开店，2资质变更，3新增品牌，4新增类目
        shopInfoAuditDTO.setStatus(0);//审核状态 0审核中，1审核通过，2审核打回，3审核不通过
        iShopInfoAuditService.insert(shopInfoAuditDTO);

        /**
         * 保存审核日志
         */
        ShopInfoAuditLogDTO shopInfoAuditLogDTO = new ShopInfoAuditLogDTO();
        Long shopInfoAuditLogId = ymlConfig.getPkId();
        shopInfoAuditLogDTO.setId(shopInfoAuditLogId);
        shopInfoAuditLogDTO.setCreateUserId(userId);
        shopInfoAuditLogDTO.setUserId(userId);
        shopInfoAuditLogDTO.setShopAuditId(shopInfoAuditId);
        shopInfoAuditLogDTO.setShopId(shopId);
        shopInfoAuditLogDTO.setStatus(0);//审核状态 0审核中(提交审核)，1审核通过，2审核打回，3审核不通过
        shopInfoAuditLogDTO.setType(1);//审核类型 0注册，1开店，2资质变更，3新增品牌，4新增类目
        iShopInfoAuditLogService.insert(shopInfoAuditLogDTO);

        /**
         * 保存店铺品牌关系审核表
         */
        if (updateBO.getShopBrandRelationSaveBOList() != null && !"".equals(updateBO.getShopBrandRelationSaveBOList())) {
            List<ShopBrandRelationSaveBO> shopBrandRelationSaveBOList = JSON.parseArray(updateBO.getShopBrandRelationSaveBOList(), ShopBrandRelationSaveBO.class);
            for (ShopBrandRelationSaveBO shopCategoryRelationSaveBO : shopBrandRelationSaveBOList) {
                ShopBrandRelationAuditDTO shopBrandRelationAuditDTO = new ShopBrandRelationAuditDTO();
                shopBrandRelationAuditDTO.setId(ymlConfig.getPkId());
                shopBrandRelationAuditDTO.setShopId(shopId);
                shopBrandRelationAuditDTO.setCreateUserId(userId);
                shopBrandRelationAuditDTO.setShopAuditId(shopInfoAuditId);
                shopBrandRelationAuditDTO.setBrandId(shopCategoryRelationSaveBO.getBrandId());
                shopBrandRelationAuditDTO.setBrandType(0);//品牌是否存在 0存在。1不存在 默认0
                shopBrandRelationAuditDTO.setStatus(0);//是否审核 0未审核、1打回、2审核通过、3审核失败
                shopBrandRelationAuditDTO.setType(1);//类型 0注册，1开店，2资质变更，3新增品牌，4新增类目
                iShopBrandRelationAuditService.insert(shopBrandRelationAuditDTO);
            }
        }

        /**
         * 保存资质审核表
         */
        List<ShopQualificationSaveBO> shopQualificationSaveBOList = JSON.parseArray(updateBO.getShopQualificationSaveBOList(), ShopQualificationSaveBO.class);
        for (ShopQualificationSaveBO shopQualificationSaveBO : shopQualificationSaveBOList) {
            ShopQualificationAuditDTO shopQualificationAuditDTO = new ShopQualificationAuditDTO();
            shopQualificationAuditDTO.setId(ymlConfig.getPkId());
            shopQualificationAuditDTO.setCreateUserId(userId);
            shopQualificationAuditDTO.setUserId(userId);
            shopQualificationAuditDTO.setShopAuditId(shopInfoAuditId);
            shopQualificationAuditDTO.setShopId(shopId);
            if (shopQualificationSaveBO.getBrandId() != null) {
                shopQualificationAuditDTO.setBrandId(shopQualificationSaveBO.getBrandId());
            }
            shopQualificationAuditDTO.setFileUrl(shopQualificationSaveBO.getFileUrl());//图片url
            shopQualificationAuditDTO.setBeginDate(shopQualificationSaveBO.getBeginDate());
            shopQualificationAuditDTO.setEndDate(shopQualificationSaveBO.getEndDate());
            //类型 0营业执照，1法人身份证，3开户许可证，4商标注册证书，5续展证明文件，6ISO认证书，7品牌授权书、
            shopQualificationAuditDTO.setType(shopQualificationSaveBO.getType());
            //审核类型 0注册，1开店，2资质变更，3新增品牌，4新增类目
            shopQualificationAuditDTO.setAuditType(1);
            shopQualificationAuditDTO.setStatus(0);//审核状态 0审核中，1审核通过，2审核打回，3审核不通过
            iShopQualificationAuditService.insert(shopQualificationAuditDTO);
        }

        /**
         * 保存品牌分类审核表
         */
        if (updateBO.getShopCategoryRelationSaveBOList() != null && !"".equals(updateBO.getShopCategoryRelationSaveBOList())) {
            List<ShopCategoryRelationSaveBO> shopCategoryRelationSaveBOList = JSON.parseArray(updateBO.getShopCategoryRelationSaveBOList(), ShopCategoryRelationSaveBO.class);
            //foreach品牌分类
            for (ShopCategoryRelationSaveBO shopCategoryRelationSaveBO : shopCategoryRelationSaveBOList) {
                ShopCategoryRelationAuditDTO shopCategoryRelationAuditDTO = new ShopCategoryRelationAuditDTO();
                shopCategoryRelationAuditDTO.setId(ymlConfig.getPkId());
                shopCategoryRelationAuditDTO.setCreateUserId(userId);
                shopCategoryRelationAuditDTO.setShopAuditId(shopInfoAuditId);
                shopCategoryRelationAuditDTO.setShopId(shopId);
                shopCategoryRelationAuditDTO.setBrandId(shopCategoryRelationSaveBO.getBrandId());
                shopCategoryRelationAuditDTO.setCategoryId(shopCategoryRelationSaveBO.getCategoryId());
                if (shopCategoryRelationSaveBO.getSort() != null) {
                    shopCategoryRelationAuditDTO.setSort(shopCategoryRelationSaveBO.getSort());
                }
                shopCategoryRelationAuditDTO.setType(1);//审核类型 0注册，1开店，2资质变更，3新增品牌，4新增类目
                shopCategoryRelationAuditDTO.setStatus(0);//审核状态 0审核中，1审核通过，2审核打回，3审核不通过
                iShopCategoryRelationAuditService.insert(shopCategoryRelationAuditDTO);
            }
        }

        /**
         * 新增品牌
         */

        if (updateBO.getShopInfoIncreaseBrandSaveBOList() != null && !"".equals(updateBO.getShopInfoIncreaseBrandSaveBOList())) {
            List<ShopInfoIncreaseBrandSaveBO> shopInfoIncreaseBrandSaveBOList = JSON.parseArray(updateBO.getShopInfoIncreaseBrandSaveBOList(), ShopInfoIncreaseBrandSaveBO.class);
            for (ShopInfoIncreaseBrandSaveBO shopInfoIncreaseBrandSaveBO : shopInfoIncreaseBrandSaveBOList) {
                /**
                 * 1.增加品牌审核表
                 * 2.增加关系审核表
                 * 3.增加资质审核表
                 * 4.增加品牌分类审核表
                 */
                /**
                 * 增加品牌审核
                 */
                BrandInfoAuditDTO brandInfoAuditDTO = new BrandInfoAuditDTO();
                Long brandAuditId = ymlConfig.getPkId();
                brandInfoAuditDTO.setId(brandAuditId);
                brandInfoAuditDTO.setCreateUserId(userId);
                brandInfoAuditDTO.setType(1);//类型 0注册，1开店，2资质变更，3新增品牌，4新增类目
                brandInfoAuditDTO.setName(shopInfoIncreaseBrandSaveBO.getName());
                brandInfoAuditDTO.setLogoUrl(shopInfoIncreaseBrandSaveBO.getLogoUrl());
                brandInfoAuditDTO.setShopId(shopId);
                brandInfoAuditDTO.setShopAuditId(shopInfoAuditId);
                brandInfoAuditDTO.setStatus(0);//状态 0未审核、1打回、2审核通过、3审核失败
                iBrandInfoAuditService.insert(brandInfoAuditDTO);

                ShopBrandRelationAuditDTO shopBrandRelationAuditDTO = new ShopBrandRelationAuditDTO();
                shopBrandRelationAuditDTO.setId(ymlConfig.getPkId());
                shopBrandRelationAuditDTO.setShopId(shopId);
                shopBrandRelationAuditDTO.setShopAuditId(shopInfoAuditId);
                shopBrandRelationAuditDTO.setBrandId(brandAuditId);
                shopBrandRelationAuditDTO.setBrandType(1);//品牌是否存在 0存在。1不存在 默认0
                shopBrandRelationAuditDTO.setStatus(0);//是否审核 0未审核、1打回、2审核通过、3审核失败
                shopBrandRelationAuditDTO.setType(1);//类型 0注册，1开店，2资质变更，3新增品牌，4新增类目
                iShopBrandRelationAuditService.insert(shopBrandRelationAuditDTO);

                /**
                 * 增加资质审核表
                 */
                List<ShopQualificationSaveBO> newQualificationSaveBOList = JSON.parseArray(shopInfoIncreaseBrandSaveBO.getShopQualificationSaveBOList(), ShopQualificationSaveBO.class);

                for (ShopQualificationSaveBO newQualificationSaveBO : newQualificationSaveBOList) {
                    ShopQualificationAuditDTO shopQualificationAuditDTO = new ShopQualificationAuditDTO();
                    shopQualificationAuditDTO.setId(ymlConfig.getPkId());
                    shopQualificationAuditDTO.setCreateUserId(userId);
                    shopQualificationAuditDTO.setUserId(userId);
                    shopQualificationAuditDTO.setShopAuditId(shopInfoAuditId);
                    shopQualificationAuditDTO.setShopId(shopId);
                    shopQualificationAuditDTO.setBrandId(brandAuditId);

                    shopQualificationAuditDTO.setFileUrl(newQualificationSaveBO.getFileUrl());//图片url
                    shopQualificationAuditDTO.setBeginDate(newQualificationSaveBO.getBeginDate());
                    shopQualificationAuditDTO.setEndDate(newQualificationSaveBO.getEndDate());
                    //类型 0营业执照，1法人身份证，3开户许可证，4商标注册证书，5续展证明文件，6ISO认证书，7品牌授权书、
                    shopQualificationAuditDTO.setType(newQualificationSaveBO.getType());
                    //审核类型 0注册，1开店，2资质变更，3新增品牌，4新增类目
                    shopQualificationAuditDTO.setAuditType(1);
                    shopQualificationAuditDTO.setStatus(0);//审核状态 0审核中，1审核通过，2审核打回，3审核不通过
                    iShopQualificationAuditService.insert(shopQualificationAuditDTO);
                }

                /**
                 * 保存品牌分类审核表
                 */
                List<ShopCategoryRelationSaveBO> newCategoryRelationSaveBOList = JSON.parseArray(shopInfoIncreaseBrandSaveBO.getShopCategoryRelationSaveBOList(), ShopCategoryRelationSaveBO.class);
                //foreach品牌分类
                for (ShopCategoryRelationSaveBO newCategoryRelationSaveBO : newCategoryRelationSaveBOList) {
                    ShopCategoryRelationAuditDTO shopCategoryRelationAuditDTO = new ShopCategoryRelationAuditDTO();
                    shopCategoryRelationAuditDTO.setId(ymlConfig.getPkId());
                    shopCategoryRelationAuditDTO.setCreateUserId(userId);
                    shopCategoryRelationAuditDTO.setShopAuditId(shopInfoAuditId);
                    shopCategoryRelationAuditDTO.setShopId(shopId);
                    shopCategoryRelationAuditDTO.setBrandId(brandAuditId);
                    shopCategoryRelationAuditDTO.setCategoryId(newCategoryRelationSaveBO.getCategoryId());
                    if (newCategoryRelationSaveBO.getSort() != null) {
                        shopCategoryRelationAuditDTO.setSort(newCategoryRelationSaveBO.getSort());
                    }
                    shopCategoryRelationAuditDTO.setType(1);//审核类型 0注册，1开店，2资质变更，3新增品牌，4新增类目
                    shopCategoryRelationAuditDTO.setStatus(0);//审核状态 0审核中，1审核通过，2审核打回，3审核不通过
                    iShopCategoryRelationAuditService.insert(shopCategoryRelationAuditDTO);
                }
            }
        }

        /**
         *  保存收款账户
         */
//        ShopReceiveCardSaveBO shopReceiveCardSaveBO = JSON.parseObject(updateBO.getShopReceiveCardSaveBO(), ShopReceiveCardSaveBO.class);
//        shopReceiveCardSaveBO.setName(shopInfoDTO.getName());
//        shopReceiveCardSaveBO.setType(1);//账户类型 0其他，1开户账户 默认0
//        iShopReceiveCardService.add(shopReceiveCardSaveBO);

        /**
         * 保存可售区域
         */
        if (updateBO.getShopSalesAreaSaveBOList() != null && !"".equals(updateBO.getShopSalesAreaSaveBOList())) {
            List<ShopSalesAreaSaveBO> shopSalesAreaSaveBOList = JSON.parseArray(updateBO.getShopSalesAreaSaveBOList(), ShopSalesAreaSaveBO.class);
            //foreach可售区域
            if (shopSalesAreaSaveBOList.size() == 0) {
                //默认全国
                ShopSalesAreaSaveBO shopSalesAreaSaveBO = new ShopSalesAreaSaveBO();
                shopSalesAreaSaveBO.setShopId(updateBO.getId());
                shopSalesAreaSaveBO.setAreaId(0L);//默认全国
                iShopSalesAreaService.add(shopSalesAreaSaveBO);
            } else {
                for (ShopSalesAreaSaveBO shopSalesAreaSaveBO : shopSalesAreaSaveBOList) {
                    iShopSalesAreaService.add(shopSalesAreaSaveBO);
                }
            }
        } else {
            ShopSalesAreaSaveBO areaSaveBO = new ShopSalesAreaSaveBO();
            areaSaveBO.setShopId(updateBO.getId());
            areaSaveBO.setAreaId(0L);//默认全国
            iShopSalesAreaService.add(areaSaveBO);
        }

        //更新卖家审核状态
        ShopInfoDTO dto = new ShopInfoDTO();
        dto.setId(shopId);
        dto.setSellerStatus(0);//开店审核状态 0创建、1审核通过、2审核打回、3，审核不通过。4重新提交。
        return this.updateById(dto);
    }

    @Override
    public CommodityEvaluationScoreVO getScore(Long id) {
        CommodityEvaluationScoreVO vo = new CommodityEvaluationScoreVO();
        CommodityEvaluationScoreVO shopScoreVO = iCommodityEvaluationService.getShopScore(id);
        vo.setServiceEvaluation(shopScoreVO.getServiceEvaluation());
        vo.setLogisticsEvaluation(shopScoreVO.getLogisticsEvaluation());
        vo.setCommodityEvaluation(shopScoreVO.getCommodityEvaluation());
        String after_sale = iOrderInfoService.getShopOrderAfterSale(id);
        vo.setAfterSale(after_sale);

        if (Float.parseFloat(shopScoreVO.getCommodityEvaluation()) >= ShoppingConstant.HIGH_EVALUATION) {
            vo.setCommodityCompared(ShoppingCodeEnum.COMPARED_HIGH.getCode());
        } else if (Float.parseFloat(shopScoreVO.getCommodityEvaluation()) < ShoppingConstant.LOW_EVALUATION) {
            vo.setCommodityCompared(ShoppingCodeEnum.COMPARED_LOW.getCode());
        } else {
            vo.setCommodityCompared(ShoppingCodeEnum.COMPARED_FAIR.getCode());
        }

        if (Float.parseFloat(shopScoreVO.getLogisticsEvaluation()) >= ShoppingConstant.HIGH_EVALUATION) {
            vo.setLogisticsCompared(ShoppingCodeEnum.COMPARED_HIGH.getCode());
        } else if (Float.parseFloat(shopScoreVO.getLogisticsEvaluation()) < ShoppingConstant.LOW_EVALUATION) {
            vo.setLogisticsCompared(ShoppingCodeEnum.COMPARED_LOW.getCode());
        } else {
            vo.setLogisticsCompared(ShoppingCodeEnum.COMPARED_FAIR.getCode());
        }

        if (Float.parseFloat(shopScoreVO.getServiceEvaluation()) >= ShoppingConstant.HIGH_EVALUATION) {
            vo.setServiceCompared(ShoppingCodeEnum.COMPARED_HIGH.getCode());
        } else if (Float.parseFloat(shopScoreVO.getServiceEvaluation()) < ShoppingConstant.LOW_EVALUATION) {
            vo.setServiceCompared(ShoppingCodeEnum.COMPARED_LOW.getCode());
        } else {
            vo.setServiceCompared(ShoppingCodeEnum.COMPARED_FAIR.getCode());
        }

        if (Float.parseFloat(after_sale) <= ShoppingConstant.HIGH_SALE_EVALUATION) {
            vo.setAfterSaleCompared(ShoppingCodeEnum.COMPARED_HIGH.getCode());
        } else if (Float.parseFloat(shopScoreVO.getServiceEvaluation()) > ShoppingConstant.LOW_SALE_EVALUATION) {
            vo.setAfterSaleCompared(ShoppingCodeEnum.COMPARED_LOW.getCode());
        } else {
            vo.setAfterSaleCompared(ShoppingCodeEnum.COMPARED_FAIR.getCode());
        }

        return vo;
    }

    @Override
    public ShopInfoDTO getByMobileName(String name, String mobile) {
        return baseMapper.getByMobileName(name, mobile);
    }

    @Override
    public ShopInfoVO selectVoByUserId(Long user_id) {
        ShopInfoVO shopInfoVO = new ShopInfoVO();
        UserInfoDTO userInfoDTO = iUserInfoService.selectById(user_id);
        if (userInfoDTO.getStatus() != 1) {
            return shopInfoVO;
        }

        Wrapper<ShopUserRelationDTO> shopUserWrapper = new EntityWrapper<>();
        shopUserWrapper.eq("user_id", user_id);
        ShopUserRelationDTO shopUserRelationDTO = iShopUserRelationService.selectOne(shopUserWrapper);
        ShopInfoDTO shopInfoDTO = this.selectById(shopUserRelationDTO.getShopId());
        if (shopInfoDTO == null) {
            return shopInfoVO;
        }

        //根据user_id获取userLogin 信息
        Wrapper<UserLoginDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", user_id);
        UserLoginDTO userLoginDTO = iUserLoginService.selectOne(wrapper);
        if (userLoginDTO == null) {
            return shopInfoVO;
        }

        //将手机号和邮箱加入vo
        BeanUtils.copyProperties(shopInfoDTO, shopInfoVO);
        shopInfoVO.setMobile(userLoginDTO.getMobile());
        shopInfoVO.setEmail(userLoginDTO.getEmail());

        return shopInfoVO;
    }

    @Override
    public HashMap<String, Integer> getVariousShop() {
        HashMap<String, Integer> map = new HashMap<String, Integer>();

        //旗舰店
        Wrapper<ShopInfoDTO> flagshipWrapper = new EntityWrapper<>();
        //店铺类型 0专营店、1专卖店、2旗舰店、3自营店
        flagshipWrapper.eq("type", 2).eq("merchant_type", 1);
        int flagshipShop = this.selectCount(flagshipWrapper);
        map.put("flagshipShop", flagshipShop);

        //专卖店
        Wrapper<ShopInfoDTO> specialtyWrapper = new EntityWrapper<>();
        //店铺类型 0专营店、1专卖店、2旗舰店、3自营店
        specialtyWrapper.eq("type", 1).eq("merchant_type", 1);
        int specialtyShop = this.selectCount(specialtyWrapper);
        map.put("specialtyShop", specialtyShop);

        //专营店
        Wrapper<ShopInfoDTO> franchiseWrapper = new EntityWrapper<>();
        //店铺类型 0专营店、1专卖店、2旗舰店、3自营店
        franchiseWrapper.eq("type", 0).eq("merchant_type", 1);
        int franchiseShop = this.selectCount(franchiseWrapper);
        map.put("franchiseShop", franchiseShop);

        return map;
    }

    @Override
    public Page<ShopInfoManageVO> queryPageList(ShopInfoBO bo) {
        Page<ShopInfoManageVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<ShopInfoManageVO> shopInfoManageVOList = baseMapper.queryPageList(page, bo);
        List<ShopInfoManageVO> newShInfoManageVo = new ArrayList<>();
        if (StrUtils.isNotEmpty(bo.getSelectType()) && shopInfoManageVOList.size() > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < shopInfoManageVOList.size(); i++) {
                if (i == shopInfoManageVOList.size() - 1) {
                    stringBuilder.append(shopInfoManageVOList.get(i).getId());
                    continue;
                }
                stringBuilder.append(shopInfoManageVOList.get(i).getId() + ",");
            }
            String url = fileUrl + "/file-client/cms/fileInfo/queryChildUserList";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
            map.add("fileUserId", ShoppingConstant.PLATE_MK_ID);
            map.add("childUserIds", stringBuilder.toString());
            map.add("type", bo.getSelectType());

            String signature = SignUtils.getSignature(map.toSingleValueMap());
            map.add("signature", signature);

            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
            //发送请求，设置请求返回数据格式为String
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class);
            String body = responseEntity.getBody();
            log.info(body);
            //Result<List<FileInfoVO>> results = (Result<List<FileInfoVO>>) JSONObject.parseObject(jsonObject.toJSONString(), Result.class);
            Result<List<FileInfoVO>> results = (Result<List<FileInfoVO>>) JSONObject.parseObject(body, Result.class);

            List<FileInfoVO> data = JSONArray.parseArray(results.getData().toString(), FileInfoVO.class);
            for (int i = 0; i < shopInfoManageVOList.size(); i++) {
                ShopInfoManageVO shopInfoManageVO = allocationFileSize(shopInfoManageVOList.get(i), data);
                shopInfoManageVO.setSelectType(bo.getSelectType());//设置类型
                newShInfoManageVo.add(shopInfoManageVO);
            }
        } else {
            newShInfoManageVo = shopInfoManageVOList;
        }
        page.setRecords(newShInfoManageVo);
        return page;
    }

    @Override
    public ShopInfoUserVO getUser(Long id) {
        ShopInfoUserVO vo = new ShopInfoUserVO();
        ShopInfoDTO shopInfoDTO=this.selectById(id);
        UserInfoDTO userInfoDTO = iUserInfoService.selectById(shopInfoDTO.getUserId());
        vo.setName(shopInfoDTO.getShopName());
        vo.setContactName(userInfoDTO.getContactName());
        Wrapper<UserLoginDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", userInfoDTO.getId());
        UserLoginDTO userLoginDTO = iUserLoginService.selectOne(wrapper);
        vo.setMobile(userLoginDTO.getMobile());
        vo.setEmail(userLoginDTO.getEmail());
        return vo;
    }

    /**
     * 为文件设置大小
     *
     * @param currentVO
     * @param data
     * @return
     */
    private ShopInfoManageVO allocationFileSize(ShopInfoManageVO currentVO, List<FileInfoVO> data) {
        for (FileInfoVO fileInfoVO : data) {
            if (fileInfoVO.getChildUserId().equals(currentVO.getId())) {
                float tempF = (float) fileInfoVO.getFileSize() / 1024 / 1024;
                currentVO.setFileSize(new BigDecimal(tempF).setScale(2, 2).floatValue());
                return currentVO;
            }
        }
        return currentVO;
    }

    @Override
    public Page<ShopInfoAbnormalVO> queryAbnormaPageList(ShopInfoBO bo) {
        Page<ShopInfoAbnormalVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<ShopInfoAbnormalVO> shopInfoAbnormalVOList = baseMapper.queryFrozenPageList(page, bo);
        for (ShopInfoAbnormalVO vo : shopInfoAbnormalVOList) {
            vo.setQualificationType(getFrozenType(vo.getId(), vo.getAdminFrozenStatus()));
        }
        page.setRecords(shopInfoAbnormalVOList);
        return page;
    }

    @Override
    public Page<ShopInfoAllVO> queryAllList(ShopInfoAllBO bo) {
        Page<ShopInfoAllVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<ShopInfoAllVO> vos = baseMapper.queryAllList(page, bo);
        if (vos!=null && vos.size()>0){
            for (ShopInfoAllVO vo : vos) {
               List<OrderInfoDTO> orderInfoDTOS =baseMapper.slectOrderByShopId(vo.getId());
              BigDecimal money= vo.getMoney();
                for (OrderInfoDTO orderInfoDTO : orderInfoDTOS) {
                    //交易额加砍价服务费
                    if (vo.getMoney()!=null){
                        if (orderInfoDTO!=null){
                            if (orderInfoDTO.getPurchaseFeeMoneyScalePrice()!=null){
                                money=money.add(orderInfoDTO.getPurchaseFeeMoneyScalePrice());
                                EntityWrapper<OrderReturnCommodityDTO> wrapper = new EntityWrapper<>();
                                wrapper.eq("order_id",orderInfoDTO.getId());
                                List<OrderReturnCommodityDTO> orderReturnCommodityDTOS = orderReturnCommodityService.selectList(wrapper);
                                //减去退款的砍价服务费
                                if (orderReturnCommodityDTOS!=null && orderReturnCommodityDTOS.size()>0){
                                    for (OrderReturnCommodityDTO orderReturnCommodityDTO : orderReturnCommodityDTOS) {
                                        if (orderReturnCommodityDTO.getPurchaseFeeMoneyScaleBackPrice()!=null){
                                            money=(money.subtract(orderReturnCommodityDTO.getPurchaseFeeMoneyScaleBackPrice()));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                vo.setMoney(money);


                List<OrderPaymentScaleDTO> list = new ArrayList<>();
                EntityWrapper<OrderPaymentTypeDTO> wrapper = new EntityWrapper<>();
                wrapper.eq("buy_shop_id",vo.getId());
                wrapper.eq("payment_type", 2);
                wrapper.eq("type", 1);
                List<OrderPaymentTypeDTO> orderPaymentTypeDTOS = orderPaymentTypeService.selectList(wrapper);
                if (orderPaymentTypeDTOS!=null && orderPaymentTypeDTOS.size()>0){
                    for (OrderPaymentTypeDTO orderPaymentTypeDTO : orderPaymentTypeDTOS) {
                        EntityWrapper<OrderPaymentScaleDTO> wrapper1 = new EntityWrapper<>();
                        wrapper1.eq("order_id",orderPaymentTypeDTO.getOrderId());
                        List<OrderPaymentScaleDTO> orderPaymentScaleDTOS = orderPaymentScaleService.selectList(wrapper1);
                        if (orderPaymentScaleDTOS!=null&& orderPaymentScaleDTOS.size()>0){
                            for (OrderPaymentScaleDTO orderPaymentScaleDTO : orderPaymentScaleDTOS) {
                                if (orderPaymentScaleDTO.getOverdueTimes()==1){
                                    list.add(orderPaymentScaleDTO);
                                }
                            }
                        }
                    }
                }
                vo.setOverdueTimes(list.size());
            }
        }
        page.setRecords(vos);
        return page;
    }

    @Override
    public ShopInfoUseStatisticsVO getUseStatistics(Long id) {
        ShopInfoUseStatisticsVO vo = baseMapper.getUseStatistics(id);
        if (vo!=null){
            if (vo.getMoney() == null) {
                vo.setMoney(BigDecimal.ZERO);
            }else {
                List<OrderInfoDTO> orderInfoDTOS =baseMapper.slectOrderByShopId(id);
                BigDecimal money= vo.getMoney();
                for (OrderInfoDTO orderInfoDTO : orderInfoDTOS) {
                    //交易额加砍价服务费
                    if (vo.getMoney()!=null){
                        if (orderInfoDTO!=null){
                            if (orderInfoDTO.getPurchaseFeeMoneyScalePrice()!=null){
                                money=money.add(orderInfoDTO.getPurchaseFeeMoneyScalePrice());
                                EntityWrapper<OrderReturnCommodityDTO> wrapper = new EntityWrapper<>();
                                wrapper.eq("order_id",orderInfoDTO.getId());
                                List<OrderReturnCommodityDTO> orderReturnCommodityDTOS = orderReturnCommodityService.selectList(wrapper);
                                //减去退款的砍价服务费
                                if (orderReturnCommodityDTOS!=null && orderReturnCommodityDTOS.size()>0){
                                    for (OrderReturnCommodityDTO orderReturnCommodityDTO : orderReturnCommodityDTOS) {
                                        if (orderReturnCommodityDTO.getPurchaseFeeMoneyScaleBackPrice()!=null){
                                            money=(money.subtract(orderReturnCommodityDTO.getPurchaseFeeMoneyScaleBackPrice()));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                vo.setMoney(money);
            }
        }else {
            vo.setMoney(BigDecimal.ZERO);
        }

        return vo;
    }

    @Override
    public boolean getbyShopName(String shopName) {
        Wrapper<ShopInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_name", shopName);
        ShopInfoDTO shopInfoDTO = new ShopInfoDTO();
        shopInfoDTO.setShopName(shopName);

        return this.update(shopInfoDTO, wrapper);
    }

    @Override
    public boolean getbyDomain(String domain) {
        Wrapper<ShopInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("domain", domain);

        ShopInfoDTO shopInfoDTO = new ShopInfoDTO();
        shopInfoDTO.setDomain(domain);

        return this.update(shopInfoDTO, wrapper);
    }

    @Override
    public ShopInfoTypeVO queryInfoByType(Integer type) {
        return baseMapper.queryInfoByType(type);
    }

    @Override
    public ShopInfoTypeVO queryInfoByIds(String shopIds) {
        String[] aShopIds = shopIds.split(",");
        return baseMapper.queryInfoByIds(aShopIds);
    }

    @Override
    public ShopInfoVO getDKInfo(ShopInfoDKBO bo) {
        return baseMapper.getDKInfo(bo);
    }

    @Override
    @Async
    public void autoUnfreeze(Long shopId) {
        //检查基础资质。
        Wrapper<ShopQualificationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", shopId);
        wrapper.andNew().eq("type", ShoppingCodeEnum.QUALIFICATION_LICENSE.getCode()).or().eq("type", ShoppingCodeEnum.QUALIFICATION_CARD.getCode()).or().eq("type", ShoppingCodeEnum.QUALIFICATION_ACCOUNT.getCode());
        List<ShopQualificationDTO> shopQualificationDTOS = shopQualificationMapper.selectList(wrapper);
        for (ShopQualificationDTO shopQualificationDTO : shopQualificationDTOS) {
            if (shopQualificationDTO.getExpireStatus().equals(2)) {
                return;
            }
        }

        //检查年费
        ShopAnnualFeeDTO shopAnnualFeeDTO = iShopAnnualFeeService.getByShopId(shopId);
        if (shopAnnualFeeDTO.getStatus().equals(0) && shopAnnualFeeDTO.getCountdownStatus().equals(2)) {
            return;
        }

        //检查保证金
        ShopEarnestMoneyDTO moneyDTO = new ShopEarnestMoneyDTO();
        moneyDTO.setShopId(shopId);
        ShopEarnestMoneyDTO shopEarnestMoneyDTO = iShopEarnestMoneyService.getByShopId(shopId);
        if (shopEarnestMoneyDTO.getStatus().equals(0) && shopEarnestMoneyDTO.getCountdownStatus().equals(2)) {
            return;
        }

        ShopInfoDTO dto = new ShopInfoDTO();
        dto.setId(shopId);
        dto.setFrozenStatus(0);//冻结状态 0未冻结，1冻结 2关店 defaultValue 0
        this.updateById(dto);
    }

    @Override
    public List<ShopInfoVO> queryList(ShopInfoQueryBO bo) {
        return baseMapper.queryList(bo);
    }

    @Override
    public Page<ShopInfoDTO> queryApiPageList(ShopInfoApiBO bo) {
        String[] areaIds = null;
        String[] initials = null;
        String[] type = null;
        if (null != bo.getAreaId() && !"".equals(bo.getAreaId())) {
            bo.setAreaId(bo.getAreaId() + ",0"); //加入全国
            areaIds = bo.getAreaId().split(",");
        }

        if (null != bo.getInitials() && !"".equals(bo.getInitials())) {
            initials = bo.getInitials().split(",");
        }

        if (null != bo.getType() && !"".equals(bo.getType())) {
            type = bo.getType().split(",");
        }

        Page<ShopInfoDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());

        return page.setRecords(baseMapper.queryApiPageList(page, type, areaIds, initials));
    }

//    public static void main(String[] args) {
//        HttpClient httpClient = new DefaultHttpClient();
//        HttpGet httpGet = new HttpGet("http://132.232.36.24/im-client/api/v1/user/status?userId=556126747909816320");
//        try {
//            HttpResponse httpResponse = httpClient.execute(httpGet);
//            org.apache.http.HttpEntity map= httpResponse.getEntity();
//            String   entityStr = EntityUtils.toString(map);
//            System.out.println("响应返回内容:"+httpResponse);
//            System.out.println("响应返回内容1:"+ entityStr);
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//
//    }
    @Override
    public ShopInfoUserVO getUser(Long id, Integer imType) {
        ShopInfoUserVO vo = new ShopInfoUserVO();
        ShopInfoDTO shopInfoDTO=this.selectById(id);
        UserInfoDTO userInfoDTO = iUserInfoService.selectById(shopInfoDTO.getUserId());
        if (imType.equals(1)){
            vo.setName(shopInfoDTO.getShopName());
        }
        if (imType.equals(0)){
            vo.setName(userInfoDTO.getName());
        }

        vo.setContactName(userInfoDTO.getContactName());

        Wrapper<UserLoginDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", userInfoDTO.getId());
        UserLoginDTO userLoginDTO = iUserLoginService.selectOne(wrapper);
        vo.setMobile(userLoginDTO.getMobile());
        vo.setEmail(userLoginDTO.getEmail());

       // if (imType.equals(0)) {
            Wrapper<ShopUserRelationDTO> dtoWrapper = new EntityWrapper<>();
            dtoWrapper.eq("user_id",userInfoDTO.getId());
            ShopUserRelationDTO shopUserRelationDTOS = iShopUserRelationService.selectOne(dtoWrapper);
            if (shopUserRelationDTOS!=null){
                Wrapper<ShopUserRelationDTO> dtoWrapper1 = new EntityWrapper<>();
                dtoWrapper1.eq("shop_id",shopUserRelationDTOS.getShopId());
                List<ShopUserRelationDTO> shopUserRelationDTOS1 = iShopUserRelationService.selectList(dtoWrapper1);
                List<ShopUserRelationDTO> shopUserRelationDTOS2= new ArrayList<>();
                for (ShopUserRelationDTO shopUserRelationDTO : shopUserRelationDTOS1) {
                    //判断哪些买家在线
                    boolean flag=false;
                    HttpClient httpClient = new DefaultHttpClient();
                    Wrapper<UserImDTO> wrapperIm = new EntityWrapper<>();
                    //类型 0买家，1卖家、2平台客服
                    wrapperIm.eq("user_id", shopUserRelationDTO.getUserId()).eq("type", imType);
                    UserImDTO userImDTO = iUserImService.selectOne(wrapperIm);
                    if (userImDTO==null){
                        continue;
                    }
                    HttpGet httpGet = new HttpGet(imUrl+userImDTO.getId());
                    log.info("响应返回内容111:"+"http://132.232.36.24/im-client/api/v1/user/status?userId="+userImDTO.getId());
                    try {
                        HttpResponse httpResponse = httpClient.execute(httpGet);
                        org.apache.http.HttpEntity map= httpResponse.getEntity();
                        String   entityStr = EntityUtils.toString(map);
                        log.info("响应返回内容:"+httpResponse);
                        log.info("响应返回内容1:"+ entityStr);
                        if (entityStr.contains("true")){
                            flag=true;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                    if (flag){
                        shopUserRelationDTOS2.add(shopUserRelationDTO);
                    }
                }


                if (shopUserRelationDTOS2!=null && shopUserRelationDTOS2.size()>0){
                    log.info("=============shopUserRelationDTOS2"+shopUserRelationDTOS2.size());
                    //有用户在线
                    //查询是否在线有主账号
                    boolean flag=false;
                    for (ShopUserRelationDTO shopUserRelationDTO : shopUserRelationDTOS2) {
                        UserInfoDTO userInfoDTO1 = iUserInfoService.selectById(shopUserRelationDTO.getUserId());
                        if (userInfoDTO1.getType()==0){
                            flag=true;
                        }
                    }
                    if (flag){
                        for (ShopUserRelationDTO shopUserRelationDTO : shopUserRelationDTOS2) {
                            UserInfoDTO userInfoDTO1 = iUserInfoService.selectById(shopUserRelationDTO.getUserId());
                            if (userInfoDTO1.getType()==0){
                                Wrapper<UserImDTO> wrapperIm = new EntityWrapper<>();
                                //类型 0买家，1卖家、2平台客服
                                wrapperIm.eq("user_id", userInfoDTO1.getId()).eq("type", imType);
                                UserImDTO userImDTO = iUserImService.selectOne(wrapperIm);
                                vo.setImId(userImDTO.getId());
                            }
                        }
                    }else {
                        //没有主账号在线
                        Wrapper<UserImDTO> wrapperIm = new EntityWrapper<>();
                        //类型 0买家，1卖家、2平台客服
                        wrapperIm.eq("user_id", shopUserRelationDTOS2.get(0).getUserId()).eq("type", imType);
                        UserImDTO userImDTO = iUserImService.selectOne(wrapperIm);
                        vo.setImId(userImDTO.getId());
                    }
                }else {
                    //没有用户在线直接找主账号
                    for (ShopUserRelationDTO shopUserRelationDTO : shopUserRelationDTOS1) {
                        UserInfoDTO userInfoDTO1 = iUserInfoService.selectById(shopUserRelationDTO.getUserId());
                        if (userInfoDTO1!=null){
                            if (userInfoDTO1.getType()==0){
                                Wrapper<UserImDTO> wrapperIm = new EntityWrapper<>();
                                //类型 0买家，1卖家、2平台客服
                                wrapperIm.eq("user_id", userInfoDTO1.getId()).eq("type", imType);
                                UserImDTO userImDTO = iUserImService.selectOne(wrapperIm);
                                vo.setImId(userImDTO.getId());
                            }
                        }
                    }
                }
            }
//        } else {
//            UserImDTO userImDTO = iUserImService.getCSbyShopId(id);
//            vo.setImId(userImDTO.getId());
//        }
        return vo;
    }

    @Override
    public boolean getVerifyCloseShop(Long id) {
        //验证是否有未完成的订单
        Integer orderNum = baseMapper.getVerifyOrder(id);
        return orderNum <= 0;
    }

    @Override
    public boolean updateCloseShop(Long id, Long userId) {
        /** 1 发送站内信
         *  2 下架商品
         *  3 更改状态
         */
        ShopInfoDTO shopInfoDTO = this.selectById(id);
        if (!shopInfoDTO.getCloseStatus().equals(0)) {
            return false;
        }

        String shopName = this.selectById(id).getShopName();
        String datenote = "<p style=\"text-align: right;\">" + DateUtils.getCurrentDateStr() + "</p >";

        String buyNote = ShoppingConstant.BUYER_CLOSE_NOTICE_ONE + shopName + ShoppingConstant.BUYER_CLOSE_NOTICE_TWO + datenote + ShoppingConstant.CLOSE_NOTICE_TAIL;
        String sellNote = ShoppingConstant.SELLER_CLOSE_NOTICE_ONE + shopName + ShoppingConstant.SELLER_CLOSE_NOTICE_TWO + datenote + ShoppingConstant.CLOSE_NOTICE_TAIL;

        //发送卖家站内信
        urgeSignContact(sellNote, id, 1, 2);
        List<Long> buyShopIds = iOrderInfoService.getListBuyerIdBySellerShopId(id);
        for (Long buyId : buyShopIds) {
            //发送买家站内信
            urgeSignContact(buyNote, buyId, 0, 2);
        }

        //下架所有商品
        iCommodityInfoService.updateStateByShopId(id);

        //更改状态
        ShopInfoDTO dto = new ShopInfoDTO();
        dto.setId(id);
        dto.setUpdateUserId(userId);
        dto.setCloseStatus(1); //关店流程状态 0未开启，1检测中（检测订单）.2关店中（关店倒计时中）
        dto.setFrozenStatus(1);//冻结状态 0未冻结，1冻结 2关店 defaultValue
        dto.setAdminFrozenStatus(1);//冻结状态 0未冻结，1冻结 2关店 defaultValue
        return this.updateById(dto);
    }

//    //添加所有省级区域
//    private void saveAllShopArea(Long shopId){
//        List<SysAreaDTO> sysAreaDTOList = iSysAreaService.getAllProvince();
//        for (SysAreaDTO dto : sysAreaDTOList){
//            ShopSalesAreaSaveBO shopSalesAreaSaveBO = new ShopSalesAreaSaveBO();
//            shopSalesAreaSaveBO.setShopId(shopId);
//            shopSalesAreaSaveBO.setAreaId(dto.getId());
//            shopSalesAreaSaveBO.setStatus(1);//状态 0使用中，1未使用
//            iShopSalesAreaService.add(shopSalesAreaSaveBO);
//        }
//    }

    private String getFrozenType(Long shopId, Integer adminFrozenStatus) {
        String frozenType = "";
        if (adminFrozenStatus.equals(1)) {
            frozenType += "admin冻结,";
        }

        //检查基础资质。
        Wrapper<ShopQualificationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", shopId);
        wrapper.andNew().eq("type", ShoppingCodeEnum.QUALIFICATION_LICENSE.getCode()).or().eq("type", ShoppingCodeEnum.QUALIFICATION_CARD.getCode()).or().eq("type", ShoppingCodeEnum.QUALIFICATION_ACCOUNT.getCode());
        List<ShopQualificationDTO> shopQualificationDTOS = shopQualificationMapper.selectList(wrapper);
        for (ShopQualificationDTO shopQualificationDTO : shopQualificationDTOS) {
            if (shopQualificationDTO.getExpireStatus().equals(2)) {
                frozenType += "基础资质过期,";
                break;
            }
        }

        //检查年费
        ShopAnnualFeeDTO shopAnnualFeeDTO = iShopAnnualFeeService.getByShopId(shopId);
        if (shopAnnualFeeDTO.getStatus().equals(0)) {
            frozenType += "年费未缴纳,";
        }

        //检查保证金
        ShopEarnestMoneyDTO shopEarnestMoneyDTO = iShopEarnestMoneyService.getByShopId(shopId);
        if (shopEarnestMoneyDTO.getStatus().equals(0)) {
            frozenType += "保证金未缴纳";
        }

        return frozenType;
    }

    private void addSms(Long shopId) {
        //发送短信
        Wrapper<UserLoginDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", this.selectById(shopId).getUserId());
        UserLoginDTO userLoginDTO = iUserLoginService.selectOne(wrapper);
        SmsInfoSaveBO smsInfoSaveBO = new SmsInfoSaveBO();
        smsInfoSaveBO.setMobile(userLoginDTO.getMobile());
        try {
            iSmsInfoService.saveFreeze(smsInfoSaveBO);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送消息 只有站内信
    private void urgeSignContact(String conunt, Long sellShopId, Integer shopType, Integer textType) {
        MessageAnnouncementSaveBO messageAnnouncementSaveBO = new MessageAnnouncementSaveBO();

        if (shopType.equals(ShoppingCodeEnum.MERCHANT_BUYER.getCode())) {
            //买家
            messageAnnouncementSaveBO.setShopType(MessageEnum.SHOP_TYPE_1.getCode());
        } else {
            messageAnnouncementSaveBO.setShopType(MessageEnum.SHOP_TYPE_2.getCode());
        }

        ResponseDTO responseDTO = new ResponseDTO();
        messageAnnouncementSaveBO.setContent(conunt);
        messageAnnouncementSaveBO.setShopId(sellShopId);
        messageAnnouncementSaveBO.setType(MessageEnum.SYS_MESSAGE.getCode());
        messageAnnouncementSaveBO.setTitle("店铺状态通知");
        messageAnnouncementSaveBO.setJumpType(MessageEnum.MESSAGE_SHOW.getCode() + "");
        messageAnnouncementSaveBO.setTextType(textType);
        messageAnnouncementSaveBO.setKey(sellShopId + "");
        responseDTO.setData(messageAnnouncementSaveBO);
        responseDTO.setMessageId(sellShopId + "");
        kafkaProducerService.senMessage(JSON.toJSONString(responseDTO), MessageTopicType.COMMENT_MESSAGE_TOPIC);
    }

    @Override
    public Result saveRegisteredShop(String shopVO) {
        RegisterShopVO registerShopVO = JSONObject.parseObject(shopVO, RegisterShopVO.class);
        RegisterShopVO.BaseInfoVO baseInfoVO = registerShopVO.getBase();
        String subStatus = registerShopVO.getSubstatus().getValue();
        String subType = registerShopVO.getAuditType().getValue();

        String sId = baseInfoVO.getShopId().getValue();
        String uId = baseInfoVO.getUserId().getValue();

        if (StringUtils.isEmpty(uId) || StringUtils.isEmpty(sId) || StringUtils.isEmpty(subStatus) || StringUtils.isEmpty(subType)) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        Long shopId = Long.parseLong(sId);
        Long userId = Long.parseLong(uId);
        Integer status = Integer.parseInt(subStatus);//提交状态 0初次提交， 4重新提交
        Integer type = Integer.parseInt(subType);// 审核类型 0注册，1开店，2资质变更，3新增品牌，4新增类目
        String shopName = baseInfoVO.getShopName().getValue();
        String name = baseInfoVO.getName().getValue();

        if (type.equals(ShoppingCodeEnum.AUDIT_TYPE_OPEN.getCode())) {
            String domain = baseInfoVO.getDomain().getValue();

            //开店验证
            if (StringUtils.isEmpty(shopName) || StringUtils.isEmpty(domain)) {
                return new Result<>(CodeEnum.FAIL_100002);
            }

            //验证是否已经加入卖家黑名单
            ShopBlacklistDTO shopBlacklistDTO = shopBlacklistService.getByShopId(shopId, ShoppingCodeEnum.BLACKLIST_OPEN.getCode());
            if (shopBlacklistDTO != null) {
                return new Result<>(CodeEnum.FAIL_100038);
            }

            //验证店铺名重复
            if (getbyShopName(shopName)) {
                return new Result<>(CodeEnum.FAIL_AddUser_3008);
            }
            //验证二级域名重复
            if (getbyDomain(domain)) {
                return new Result<>(CodeEnum.FAIL_AddUser_3009);
            }

            //验证是否已经处于开店状态
            ShopInfoDTO shopInfoDTO = this.selectById(sId);
            if (status.equals(ShoppingCodeEnum.AUDIT_CREATE.getCode()) && shopInfoDTO.getSellerStatus() != ShoppingCodeEnum.AUDIT_NULL.getCode()) {
                return new Result<>(CodeEnum.FAIL_AddUser_3010);
            }

            //跟新店铺状态
            ShopInfoDTO dto = new ShopInfoDTO();
            dto.setId(shopId);
            dto.setSellerStatus(status);//开店审核状态 0创建、1审核通过、2审核打回、3，审核不通过。4重新提交。
            this.updateById(dto);
        }

        if (status.equals(ShoppingCodeEnum.AUDIT_CREATE.getCode())) {
            addAudit(userId, shopId, name, shopName, shopVO, status, type);
        } else {
            RegisterShopVO.AuditInfoVO auditInfoVO = registerShopVO.getAudit();
            updateAudit(auditInfoVO.getAuditId().getValue(), shopName, shopVO, status);
        }
        return new Result<>();
    }

    @Override
    public List<EsShopDTO> queryEsShop(String id) {
        if ("0".equals(id)) {
            Wrapper<ShopInfoDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("merchant_type", 1)
                    .eq("frozen_status", 0)
                    .eq("admin_frozen_status", 0)
                    .eq("check_agreement_status",1);
            List<ShopInfoDTO> selectList = this.selectList(wrapper);
            if (isNull(selectList)) {
                return null;
            }
            List<ShopEsVO> result = new ArrayList<>();
            for (ShopInfoDTO dto : selectList) {
                Long shopId = dto.getId();
                // 根据shopId查询出被收藏数
                Integer beCollectShopCount = iShopCollectService.getBeCollectShopCount(shopId);
                // 根据shopId查询出商品总数
                Integer commodityNumByShopId = iCommodityInfoService.getCommodityNumByShopId(shopId);
                // 根据shopId查询出是否有新品
                Integer isNew = iCommodityInfoService.getShopCommodityIsNew(shopId);
                // 根据shopId查询出好评率
                String shopPraise = iCommodityEvaluationService.getShopPraise(shopId);
                ShopEsVO vo = new ShopEsVO();
                BeanUtils.copyProperties(dto, vo);
                vo.setCollectNum(beCollectShopCount);
                vo.setIsNew(isNew);
                vo.setCommodityNum(commodityNumByShopId);
                vo.setPositiveRate(shopPraise);
                result.add(vo);
            }
            return this.createEsShopMapping(result);
        }
        ShopInfoDTO select = this.selectById(id);
        if (select == null) {
            return null;
        }
        List<ShopEsVO> resultA = new ArrayList<>();
        Long shopId = select.getId();
        // 根据shopId查询出被收藏数
        Integer beCollectShopCount = iShopCollectService.getBeCollectShopCount(shopId);
        // 根据shopId查询出商品总数
        Integer commodityNumByShopId = iCommodityInfoService.getCommodityNumByShopId(shopId);
        // 根据shopId查询出是否有新品
        Integer isNew = iCommodityInfoService.getShopCommodityIsNew(shopId);
        // 根据shopId查询出好评率
        String shopPraise = iCommodityEvaluationService.getShopPraise(shopId);
        ShopEsVO voA = new ShopEsVO();
        BeanUtils.copyProperties(select, voA);
        voA.setCollectNum(beCollectShopCount);
        voA.setIsNew(isNew);
        voA.setCommodityNum(commodityNumByShopId);
        voA.setPositiveRate(shopPraise);
        resultA.add(voA);
        return this.createEsShopMapping(resultA);
    }

    @Override
    public List<ShopUpdateAuditVO> getOpenShopMessage(Long shopId, Integer type) {
        // type = 1,下一步数据，type = 2,审核中数据
        // 查询店铺
        ShopInfoDTO infoDTO = this.selectById(shopId);
        if (infoDTO == null) {
            return null;
        }
        List<ShopUpdateAuditVO> list = new ArrayList<>();
        if (type.equals(1)) {
            ShopUpdateAuditVO openShopDate = this.getOpenShopDate(infoDTO);
            list.add(openShopDate);
        } else {
            // 获取最近一次变更审核的数据
            Wrapper<AuditDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("shop_id", infoDTO.getId());
            wrapper.eq("type", 5);
            wrapper.orderBy("create_time", false);
            AuditDTO dto = auditService.selectOne(wrapper);
            if (dto == null) {
                return null;
            }
            ShopUpdateAuditVO auditVO = new ShopUpdateAuditVO();
            BeanUtils.copyProperties(dto, auditVO);
            auditVO.setChangeStatus(infoDTO.getChangeStatus());
            auditVO.setOriginalShopType(infoDTO.getType());
            list.add(auditVO);
        }
        return list;
    }

    /**
     * @return : com.ztgf.shopping.models.vo.shop.ShopUpdateAuditVO
     * @Author :chenyu.wang
     * @Description : 获取店铺开店资质
     * @Date : 2021.01.29 09:36
     * @Param : [shopId]
     **/
    private ShopUpdateAuditVO getOpenShopDate(ShopInfoDTO infoDTO) {
        ShopUpdateAuditVO vo = new ShopUpdateAuditVO();
        vo.setChangeStatus(infoDTO.getChangeStatus());
        vo.setOriginalShopType(infoDTO.getType());
        vo.setUserId(infoDTO.getUserId());
        vo.setShopId(infoDTO.getId());
        vo.setName(infoDTO.getName());
        vo.setShopName(infoDTO.getShopName());
        RegisterShopVO registerShopVO = new RegisterShopVO();
        // 提交状态 0初次提交， 4重新提交
        ProcessVO substatus = new ProcessVO();
        substatus.setValue("0");
        registerShopVO.setSubstatus(substatus);
        // 审核类型 0注册，1开店，2资质变更，3新增品牌，4新增类目，5店铺变更
        ProcessVO auditType = new ProcessVO();
        auditType.setValue("1");
        registerShopVO.setAuditType(auditType);
        // 基本信息
        RegisterShopVO.BaseInfoVO shopBaseDate = this.getShopBaseDate(infoDTO);
        registerShopVO.setBase(shopBaseDate);
        // 基本资质
        List<RegisterShopVO.QualificationInfoVO> qualificationInfoVOS = this.getBasicQualifications(infoDTO);
        registerShopVO.setQualificationInfoVOList(qualificationInfoVOS);
        // 品牌资质
        List<RegisterShopVO.BrandAuditVO> brandDate = this.getBrandDate(infoDTO);
        registerShopVO.setBrandAuditVOList(brandDate);
        String param = JSONObject.toJSONString(registerShopVO);
        log.info("店铺开店信息:{}", param);
        vo.setParams(param);
        return vo;
    }


    /**
     * @return : java.util.List<com.ztgf.shopping.models.vo.audit.RegisterShopVO.BrandAuditVO>
     * @Author :chenyu.wang
     * @Description : 获取品牌资质
     * @Date : 2021.01.29 11:59
     * @Param : [shopInfoDTO]
     **/
    private List<RegisterShopVO.BrandAuditVO> getBrandDate(ShopInfoDTO shopInfoDTO) {
        // 查询店铺品牌关联
        Wrapper<ShopBrandRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", shopInfoDTO.getId()).eq("status", 0);
        List<ShopBrandRelationDTO> relationDTOList = iShopBrandRelationService.selectList(wrapper);
        if (CustomizeUtil.listIsNull(relationDTOList)) {
            return null;
        }
        List<RegisterShopVO.BrandAuditVO> list = new ArrayList<>();
        RegisterShopVO registerShopVO = new RegisterShopVO();
        for (ShopBrandRelationDTO brandRelationDTO : relationDTOList) {
            //
            RegisterShopVO.BrandAuditVO brandAuditVO = registerShopVO.new BrandAuditVO();
            // 品牌id
            ProcessVO brandId = new ProcessVO();
            brandId.setValue(brandRelationDTO.getBrandId().toString());
            brandAuditVO.setId(brandId);
            // 品牌名称
            BrandInfoDTO brandInfoDTO = iBrandInfoService.selectById(brandRelationDTO.getBrandId());
            ProcessVO brandName = new ProcessVO();
            brandName.setValue(brandInfoDTO.getName());
            brandAuditVO.setName(brandName);
            // 品牌log
            ProcessVO log = new ProcessVO();
            log.setValue(brandInfoDTO.getLogoUrl());
            brandAuditVO.setLogoUrl(log);
            // 状态
            ProcessVO status = new ProcessVO();
            status.setValue("1");
            brandAuditVO.setStatus(status);
            // 类目审核状态
            ProcessVO categoryStatus = new ProcessVO();
            categoryStatus.setValue("1");
            brandAuditVO.setCategoryStatus(categoryStatus);
            // 品牌资质
            List<RegisterShopVO.QualificationInfoVO> brandQList = new ArrayList<>();
            Wrapper<ShopQualificationDTO> brandWrapper = new EntityWrapper<>();
            brandWrapper.eq("shop_id", shopInfoDTO.getId())
                    .eq("brand_id", brandRelationDTO.getBrandId());
            List<ShopQualificationDTO> dtoList = shopQualificationMapper.selectList(brandWrapper);
            if (CustomizeUtil.listIsNotNull(dtoList)) {
                for (ShopQualificationDTO shopQualificationDTO : dtoList) {
                    RegisterShopVO.QualificationInfoVO qualificationInfoVO = new RegisterShopVO.QualificationInfoVO();
                    // 状态
                    ProcessVO statusA = new ProcessVO();
                    statusA.setValue("1");
                    qualificationInfoVO.setStatus(statusA);
                    // fileUrl
                    ProcessVO fileUrl = new ProcessVO();
                    fileUrl.setValue(shopQualificationDTO.getFileUrl());
                    qualificationInfoVO.setFileUrl(fileUrl);
                    // 开始时间
                    if (shopQualificationDTO.getBeginDate() != null) {
                        String startDate = DateUtils.dateToStr(shopQualificationDTO.getBeginDate());
                        ProcessVO beginDate = new ProcessVO();
                        beginDate.setValue(startDate);
                        qualificationInfoVO.setBeginDate(beginDate);
                    }
                    // 结束时间
                    if (shopQualificationDTO.getEndDate() != null) {
                        String endDate = DateUtils.dateToStr(shopQualificationDTO.getEndDate());
                        ProcessVO endDates = new ProcessVO();
                        endDates.setValue(endDate);
                        qualificationInfoVO.setEndDate(endDates);
                    }
                    // 类型
                    ProcessVO qtype = new ProcessVO();
                    qtype.setValue(shopQualificationDTO.getType().toString());
                    qualificationInfoVO.setQtype(qtype);
                    brandQList.add(qualificationInfoVO);
                }
                brandAuditVO.setQualificationInfoVOList(brandQList);
            }
            // 品牌类目
            List<RegisterShopVO.BrandCategoryVO> brandCategoryVOList = new ArrayList<>();
            Wrapper<ShopCategoryRelationDTO> relationDTOWrapper = new EntityWrapper<>();
            relationDTOWrapper.eq("shop_id", shopInfoDTO.getId()).eq("brand_id", brandRelationDTO.getBrandId());
            List<ShopCategoryRelationDTO> categoryRelationDTOList = iShopCategoryRelationService.selectList(relationDTOWrapper);
            if (CustomizeUtil.listIsNotNull(categoryRelationDTOList)) {
                for (ShopCategoryRelationDTO shopCategoryRelationDTO : categoryRelationDTOList) {
                    RegisterShopVO.BrandCategoryVO brandCategoryVO = new RegisterShopVO.BrandCategoryVO();
                    // 类目ID
                    ProcessVO categoryId = new ProcessVO();
                    categoryId.setValue(shopCategoryRelationDTO.getCategoryId().toString());
                    brandCategoryVO.setCategoryId(categoryId);
                    // 状态
                    ProcessVO statusB = new ProcessVO();
                    statusB.setValue("1");
                    brandCategoryVO.setStatus(statusB);
                    brandCategoryVOList.add(brandCategoryVO);
                }
                brandAuditVO.setBrandCategoryVOList(brandCategoryVOList);
            }
            list.add(brandAuditVO);
        }
        return list;
    }

    /**
     * @return : java.util.List<com.ztgf.shopping.models.vo.audit.RegisterShopVO.QualificationInfoVO>
     * @Author :chenyu.wang
     * @Description : 店铺变更下一步获取店铺基本资质
     * @Date : 2021.01.29 10:45
     * @Param : [shopInfoDTO]
     **/
    private List<RegisterShopVO.QualificationInfoVO> getBasicQualifications(ShopInfoDTO shopInfoDTO) {
        // 只需要查询开户许可证
//        Wrapper wrapper = new EntityWrapper<>();
//        wrapper.eq("shop_id", shopInfoDTO.getId());
//        wrapper.eq("type", 2);
//        wrapper.eq("expire_status", 0);

        ShopQualificationDTO dto = new ShopQualificationDTO();
        dto.setShopId(shopInfoDTO.getId());
        dto.setType(2);
        dto.setExpireStatus(0);
        ShopQualificationDTO qualificationDTO = shopQualificationMapper.selectOne(dto);
        if (qualificationDTO == null) {
            return null;
        }
        List<RegisterShopVO.QualificationInfoVO> list = new ArrayList<>();
        RegisterShopVO.QualificationInfoVO infoVO = new RegisterShopVO.QualificationInfoVO();
        // url
        ProcessVO fileUrl = new ProcessVO();
        fileUrl.setValue(qualificationDTO.getFileUrl());
        infoVO.setFileUrl(fileUrl);
        // 类型
        ProcessVO qtype = new ProcessVO();
        qtype.setValue(qualificationDTO.getType().toString());
        infoVO.setQtype(qtype);
        // 状态
        ProcessVO status = new ProcessVO();
        status.setValue("1");
        infoVO.setStatus(status);
        list.add(infoVO);
        return list;
    }

    /**
     * @return : com.ztgf.shopping.models.vo.audit.RegisterShopVO.BaseInfoVO
     * @Author :chenyu.wang
     * @Description : 店铺变更获取店铺基本信息
     * @Date : 2021.01.29 10:27
     * @Param : [shopInfoDTO]
     **/
    private RegisterShopVO.BaseInfoVO getShopBaseDate(ShopInfoDTO shopInfoDTO) {
        // 店铺基本信息
        RegisterShopVO.BaseInfoVO baseInfo = new RegisterShopVO.BaseInfoVO();
        // 用户id
        ProcessVO user = new ProcessVO();
        user.setValue(shopInfoDTO.getUserId().toString());
        baseInfo.setUserId(user);
        // 店铺id
        ProcessVO shop = new ProcessVO();
        shop.setValue(shopInfoDTO.getId().toString());
        baseInfo.setShopId(shop);
        // 二级域名
        ProcessVO domain = new ProcessVO();
        domain.setValue(shopInfoDTO.getDomain());
        baseInfo.setDomain(domain);
        // 店铺类型 0专营店、1专卖店、2旗舰店、3自营店
        ProcessVO type = new ProcessVO();
        type.setValue(shopInfoDTO.getType().toString());
        baseInfo.setType(type);
        // 公司名称
        ProcessVO name = new ProcessVO();
        name.setValue(shopInfoDTO.getName());
        baseInfo.setName(name);
        // 店铺名称
        ProcessVO shopName = new ProcessVO();
        shopName.setValue(shopInfoDTO.getShopName());
        baseInfo.setShopName(shopName);
        // 店铺本名
        ProcessVO shopRealName = new ProcessVO();
        shopRealName.setValue(shopInfoDTO.getShopRealName());
        baseInfo.setShopRealName(shopRealName);
        // 店铺简称
        ProcessVO shopAbbreviation = new ProcessVO();
        shopAbbreviation.setValue(shopInfoDTO.getShopAbbreviation());
        baseInfo.setShopAbbreviation(shopAbbreviation);
        // 法人身份证号
        ProcessVO idCard = new ProcessVO();
        idCard.setValue(shopInfoDTO.getIdCard());
        baseInfo.setIdCard(idCard);
        // 获取开户账号信息
        ShopReceiveCardDTO bankDto = shopReceiveCardService.getOpenByShopId(shopInfoDTO.getId());
        if (bankDto != null) {
            ProcessVO bankName = new ProcessVO();
            bankName.setValue(bankDto.getBankName());
            baseInfo.setBankName(bankName);
            ProcessVO bankCardNo = new ProcessVO();
            bankCardNo.setValue(bankDto.getBankCardNo());
            baseInfo.setBankCardNo(bankCardNo);
            ProcessVO bankAddress = new ProcessVO();
            bankAddress.setValue(bankDto.getBankAddress());
            baseInfo.setBankAddress(bankAddress);
        }
        return baseInfo;
    }

    @Override
    public Result<?> updateShopTypeCommit(String shopVO) {
        log.info("店铺变更提交的数据:{}", shopVO);
        RegisterShopVO registerShopVO = JSONObject.parseObject(shopVO, RegisterShopVO.class);
        // 基本信息
        RegisterShopVO.BaseInfoVO base = registerShopVO.getBase();
        // 提交状态 0初次提交， 4重新提交
        String submitState = registerShopVO.getSubstatus().getValue();
        // 审核类型 0注册，1开店，2资质变更，3新增品牌，4新增类目，5店铺变更
        String auditType = registerShopVO.getAuditType().getValue();
        String sId = base.getShopId().getValue();
        String uId = base.getUserId().getValue();
        if (StringUtils.isEmpty(uId) || StringUtils.isEmpty(sId) || StringUtils.isEmpty(submitState) || StringUtils.isEmpty(auditType)) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        // 获取原来的店铺信息
        ShopInfoDTO select = this.selectById(sId);
        if (select == null) {
            return new Result<>(CodeEnum.SHOP_CART_SHOP);
        }
        // 店铺id
        Long shopId = select.getId();
        // userId
        Long userId = Long.parseLong(uId);
        // 提交状态 0初次提交， 4重新提交
        Integer status = Integer.parseInt(submitState);
        // 审核类型 0注册，1开店，2资质变更，3新增品牌，4新增类目，5店铺变更
        Integer type = Integer.parseInt(auditType);
        // 店铺名称
        String shopName = base.getShopName().getValue();
        // 公司名称
        String name = base.getName().getValue();
        // 域名
        String domain = base.getDomain().getValue();
        // 店铺类型
        Integer shopType = Integer.parseInt(base.getType().getValue());
        // 验证是否重复提交
        boolean checkCommit = this.checkCommit(shopId);
        if (!checkCommit) {
            return new Result<>(CodeEnum.AFTER_SALE_ORDER_ERROR_320002);
        }
        // 验证是否在可变更时间
        if (select.getChangeTime() != null) {
            // 获取变更的一年后的时间
            Date oneYearTime = CustomizeUtil.getOneYearTime(select.getChangeTime());
            // 现在的时间
            Date date = new Date();
            if (date.before(oneYearTime)) {
                return new Result<>(CodeEnum.SHOP_UPDATE_TIME_ERROR);
            }
            // 如果可以变更，将原来的变更时间清空
            baseMapper.updateChangeTime(shopId);
        }
        // 验证可变的店铺类型
        if (!select.getType().equals(shopType)) {
            if (select.getType().equals(0)) {
                return new Result<>(CodeEnum.SHOP_UPDATE_ERROR);
            }
        }
        // 验证店铺名称和二级域名
        if (CustomizeUtil.strIsNull(shopName) || CustomizeUtil.strIsNull(domain)) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        //验证是否已经加入卖家黑名单
        ShopBlacklistDTO shopBlacklistDTO = shopBlacklistService.getByShopId(shopId, ShoppingCodeEnum.BLACKLIST_OPEN.getCode());
        if (shopBlacklistDTO != null) {
            return new Result<>(CodeEnum.FAIL_100038);
        }
        // 验证店铺名称是否重复
        if (!select.getShopName().equals(shopName)) {
            if (this.getbyShopName(shopName)) {
                return new Result<>(CodeEnum.FAIL_AddUser_3008);
            }
        }
        //验证二级域名重复
        if (!select.getDomain().equals(domain)) {
            if (getbyDomain(domain)) {
                return new Result<>(CodeEnum.FAIL_AddUser_3009);
            }
        }
        // 更新店铺状态
        ShopInfoDTO updateDto = new ShopInfoDTO();
        updateDto.setId(shopId);
        //店铺变更状态:0未提交,1审核通过,2审核不通过,3审核打回,4审核中,5重新提交
        if (status.equals(0)) {
            updateDto.setChangeStatus(4);
        } else {
            updateDto.setChangeStatus(5);
        }
        this.updateById(updateDto);
        if (status.equals(0)) {
            // 先删除原有不通过的信息
            Wrapper<AuditDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("shop_id", shopId);
            wrapper.eq("type", 5);
            wrapper.orderBy("create_time", false);
            auditService.delete(wrapper);
            this.addAudit(userId, shopId, name, shopName, shopVO, status, type);
        } else {
            RegisterShopVO.AuditInfoVO auditInfoVO = registerShopVO.getAudit();
            this.updateAudit(auditInfoVO.getAuditId().getValue(), shopName, shopVO, status);
        }
        return new Result<>(CodeEnum.SUCCESS);
    }

    @Override
    public Map<String, Integer> getCheckUpdateShop(Long shopId) {
//        // 0允许变更，1不允许变更
        ShopInfoDTO shopInfo = this.selectById(shopId);
        if (shopInfo == null) {
            return null;
        }
        Map<String, Integer> map = new HashMap<>();
        // 店铺类型
        map.put("shopType", shopInfo.getType());
        // 是否在一年内
        if (shopInfo.getChangeTime() != null) {
            // 获取变更时间一年后的时间
            Date oneYearTime = CustomizeUtil.getOneYearTime(shopInfo.getChangeTime());
            Date date = new Date();
            if (date.before(oneYearTime)) {
                map.put("isOneYear", 1);
                map.put("isCheckCommit", 1);
            } else {
                map.put("isOneYear", 0);
                map.put("isCheckCommit", 0);
            }

        } else {
            map.put("isOneYear", 0);
            // 查询是否有提交审核中的变更申请
            Wrapper<AuditDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("shop_id", shopInfo.getId());
            wrapper.eq("type", 5);
            wrapper.orderBy("create_time", false);
            AuditDTO dto = auditService.selectOne(wrapper);
            if (dto == null) {
                map.put("isCheckCommit", 0);
            } else {
                if (dto.getStatus().equals(0) || dto.getStatus().equals(1) || dto.getStatus().equals(4) || dto.getStatus().equals(2)) {
                    map.put("isCheckCommit", 1);
                } else {
                    map.put("isCheckCommit", 0);
                }
            }
        }
        return map;
    }

    @Override
    public Integer updateChangeTime(Long shopId) {
        return baseMapper.updateChangeTime(shopId);
    }

    @Override
    public List<ShopInfoTypeVO> queryshopInfoByType(String shopIds, Integer type, Integer pageNum, Integer pageSize) {
        return baseMapper.queryshopInfoByType(shopIds,type,pageNum,pageSize);
    }

    @Override
    public Page<ShopInfoVO> queryPageListBySms(ShopInfoQueryBO bo) {
        Page<ShopInfoVO> page = new Page<> (bo.getPageNo (),bo.getPageSize ());
        List<ShopInfoVO> vos = baseMapper.queryPageListByNoticeId(page, bo);
        if (bo.getMerchantType ()!= null && bo.getMerchantType ().equals(1)){
            for (ShopInfoVO shopInfoVO: vos) {
                shopInfoVO.setName (shopInfoVO.getShopName ());
            }
        }
        page.setRecords(vos);
        return page;
    }

    @Override
    public ShopInfoDTO getByUserId(Long userId) {
        return this.baseMapper.getByUserId(userId);
    }

    @Override
    public Page<ShopOverdueVO> queryOverdueList(ShopOverdueBO bo) {
        Page<ShopOverdueVO> page = new Page<>(bo.getPageNo (),bo.getPageSize ());
        List<ShopOverdueVO> list=this.baseMapper.queryOverdueList(page,bo);
        if (list!=null && list.size()>0){
            for (ShopOverdueVO shopOverdueVO : list) {
                EntityWrapper<OrderPaymentScaleDTO> wrapper = new EntityWrapper<>();
                wrapper.eq("order_id",shopOverdueVO.getOrderId());
                wrapper.eq("overdue_times",1);
                List<OrderPaymentScaleDTO> list1 = orderPaymentScaleService.selectList(wrapper);
                if (list1!=null && list1.size()>0){
                    shopOverdueVO.setOverdueTimes(list1.size());
                }
            }
        }
        page.setRecords(list);
        return page;
    }

    /**
     * @Description: 处理Es店铺映射dto
     * @Author: chenyu.wang
     * @Params: [list]
     * @Date: 2020.12.22 15:17
     */
    private List<EsShopDTO> createEsShopMapping(List<ShopEsVO> list) {
        List<EsShopDTO> result = new ArrayList<>();
        for (ShopEsVO vo : list) {
            EsShopDTO dto = new EsShopDTO();
            dto.setId(vo.getId());
            if (StringUtils.isNotBlank(vo.getName())) {
                dto.setName(vo.getName());
            }
            if (StringUtils.isNotBlank(vo.getLogo())) {
                dto.setLogo(vo.getLogo());
            }
            if (StringUtils.isNotBlank(vo.getDomain())) {
                dto.setDomain(vo.getDomain());
            }
            if (StringUtils.isNotBlank(vo.getQrCode())) {
                dto.setQrCode(vo.getQrCode());
            }
            if (StringUtils.isNotBlank(vo.getNotes())) {
                dto.setNotes(vo.getNotes());
            }
            if (StringUtils.isNotBlank(vo.getAreaId())) {
                dto.setAreaId(vo.getAreaId());
            }
            if (StringUtils.isNotBlank(vo.getAddress())) {
                dto.setAddress(vo.getAddress());
            }
            dto.setType(vo.getType());
            dto.setMerchantType(vo.getMerchantType());
            dto.setIntegral(vo.getIntegral());
            dto.setLevel(vo.getLevel());
            dto.setShopName(vo.getShopName());
            dto.setShopNameIkSmart(vo.getShopName());
            dto.setShopNameIkMaxWord(vo.getShopName());
            dto.setShop_name_standard(vo.getShopName());
            dto.setShopAbbreviation(vo.getShopAbbreviation());
            dto.setShop_abbreviation_ik(vo.getShopAbbreviation());
            dto.setShop_abbreviation_standard(vo.getShopAbbreviation());
            dto.setTempletId(vo.getTempletId());
            dto.setBuyerRank(vo.getBuyerRank());
            dto.setCollectNum(vo.getCollectNum());
            dto.setCommodityNum(vo.getCommodityNum());
            dto.setIsNew(vo.getIsNew());
            dto.setPositiveRate(vo.getPositiveRate());
            result.add(dto);
        }
        return result;
    }

    private void updateAudit(String auditId, String shopName, String shopVO, Integer status) {
        AuditDTO auditDTO = new AuditDTO();
        auditDTO.setId(Long.parseLong(auditId));
        auditDTO.setParams(shopVO);
        auditDTO.setShopName(shopName);
        auditDTO.setStatus(status);
        auditService.update(auditDTO);
    }

    private void addAudit(Long userId, Long shopId, String name, String shopName, String shopVO, Integer status, Integer type) {
        AuditDTO auditDTO = new AuditDTO();
        auditDTO.setCreateUserId(userId);
        auditDTO.setUserId(userId);
        auditDTO.setParams(shopVO);
        auditDTO.setShopId(shopId);
        auditDTO.setName(name);
        auditDTO.setShopName(shopName);
        auditDTO.setType(type);
        auditDTO.setStatus(status);
        auditService.add(auditDTO);
    }

    /**
     * @return : boolean
     * @Author :chenyu.wang
     * @Description : 验证店铺变更是否重复提交
     * @Date : 16:19 2021.01.20
     * @Param : [shopId]
     **/
    private boolean checkCommit(Long shopId) {
        Wrapper<AuditDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", shopId).eq("type", 5);
        wrapper.andNew().eq("status", 0).or().eq("status", 1);
        wrapper.orderBy("create_time", false);
        AuditDTO selectOne = auditService.selectOne(wrapper);
        return selectOne == null;
    }

    /**
     * @return : com.ztgf.shopping.models.vo.shop.ShopUpdateAuditVO
     * @Author :chenyu.wang
     * @Description : 获取店铺最近一次的开店审核通过信息
     * @Date : 2021.01.26 18:06
     * @Param :
     **/
    private ShopUpdateAuditVO getLatelyOpenShopMsg(ShopInfoDTO infoDTO) {
        AuditDTO shopMessage = baseMapper.getOpenShopMessage(infoDTO.getId());
        if (shopMessage == null) {
            return null;
        }
        ShopUpdateAuditVO auditVO = new ShopUpdateAuditVO();
        BeanUtils.copyProperties(shopMessage, auditVO);
        auditVO.setChangeStatus(infoDTO.getChangeStatus());
        auditVO.setOriginalShopType(infoDTO.getType());
        return auditVO;
    }

    /**
     * @return : com.ztgf.shopping.models.vo.shop.ShopUpdateAuditVO
     * @Author :chenyu.wang
     * @Description : 获取店铺最近一次店铺变更信息
     * @Date : 2021.01.26 18:12
     * @Param : [infoDTO]
     **/
    private ShopUpdateAuditVO getLatelyShopChangeMsg(ShopInfoDTO infoDTO) {
        Wrapper<AuditDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", infoDTO.getId());
        wrapper.eq("type", 5);
        wrapper.orderBy("create_time", false);
        AuditDTO dto = auditService.selectOne(wrapper);
        if (dto == null) {
            return null;
        }
        if (dto.getStatus().equals(3)) {
            // 审核不通过后返回最近一次开店的数据
            return this.getLatelyOpenShopMsg(infoDTO);
        }
        // 其他状态返回最近一次变更提交的记录
        ShopUpdateAuditVO auditVO = new ShopUpdateAuditVO();
        BeanUtils.copyProperties(dto, auditVO);
        auditVO.setChangeStatus(infoDTO.getChangeStatus());
        auditVO.setOriginalShopType(infoDTO.getType());
        return auditVO;
    }


}
